//
//  MeatOrderViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/24.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatOrderViewController.h"
#import "MeatPayViewController.h"
#import "AddressViewController.h"


#import "MeatOrderListCell.h"
#import "MeatOrderLocationCell.h"
#import "MeatOrderPriceCell.h"

#import "MeatPayView.h"
#import "MeatTipLabel.h"

#import "MeatOrderBox.h"
#import "MeatMarketApi.h"
#import "Address.h"
#import "MeatOrderSumbitParam.h"


@interface MeatOrderViewController ()<AddressViewControllerDelegate>


/**
 tap
 */
@property (nonatomic, strong) UITapGestureRecognizer *tap;


/**
 当前是第几个section
 */
@property (nonatomic, assign) NSInteger currentIndex;


/**
 提示标签
 */
@property (nonatomic, strong) MeatTipLabel *tipLabel;


/**
 footer
 */
@property (nonatomic, strong) MeatPayView *footer;


@property (nonatomic, strong) MeatMarketApi *meatApi;


@property (nonatomic, strong) MeatPayOrderModel *model;


@property (nonatomic, strong) AddressList *addressModel;

@property (nonatomic, strong) NSMutableArray *locations;

@property (nonatomic, strong) ListParam *listParam;

@property (nonatomic, strong) MeatOrderSumbitParam *sumbitParam;

@property (nonatomic, strong) UIButton *anonymousBtn;



@end

@implementation MeatOrderViewController

#pragma mark - lifecycle methods

- (void)setupUI
{
    
    self.currentIndex = 0;

    {
        self.baseNavView.navTitleLabel.text = @"确认订单";
    }
    
    {
        [self.view addSubview:self.tipLabel];
        [self.view addSubview:self.footer];
        [self.view addSubview:self.anonymousBtn];
    }
    
    
    [self addkeyBoardNotification];
    
}


- (void)setupLayout
{
    _footer.mj_y = KScreenHeight - _footer.height;
    _tipLabel.mj_y = _footer.top - _tipLabel.height;
    
    {
        self.tableView.mj_y = self.baseNavView.bottom;
        self.tableView.height = _tipLabel.top  - 5 - TJ_NavBarHeight;
    }
    
    {
        _anonymousBtn.size = CGSizeMake(90, 48);
        _anonymousBtn.mj_x = 15;
        _anonymousBtn.mj_y = _tipLabel.top - _anonymousBtn.height;
    }
}


#pragma mark - networking methods

- (void)initData{
    
    [self locationData];
    [self orderData];
}


- (void)locationData{
    
    NSNumber *memberId = [UserInfoDataProvider sharedInstance].userInfo.memberId;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getAddressListWithMemberId:memberId] subscribeNext:^(AddressList * _Nullable addressList) {
        @strongify(self);
        
        self.addressModel = addressList;
        [self orderData];
        
    } error:^(NSError * _Nullable error) {
        [self loadErrorData];
    }];
}


- (void)orderData{
    
    @weakify(self);
    [[self.meatApi getMeatPayTypeByShopId:self.shopId] subscribeNext:^(MeatPayOrderModel * _Nullable model) {
        @strongify(self);
        
        self.model = model;
        __block float price = 0;
        __block NSMutableArray *ids = [NSMutableArray array];
        [model.list enumerateObjectsUsingBlock:^(MeatPayOrderItem * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
            [item.meets enumerateObjectsUsingBlock:^(Meats * _Nonnull meats, NSUInteger idx, BOOL * _Nonnull stop) {
                [meats.list enumerateObjectsUsingBlock:^(MeatsItem * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
                    price += [obj.nowPrice floatValue];
                    [ids addObject:obj.advanceSaleId];
                }];
            }];
        }];
        
        
#pragma mark  - 提交参数
        {
            self.sumbitParam.pigId = model.list[0].pigId;
            self.sumbitParam.advanceSaleIds = [ids copy];
            self.listParam.advanceSaleId = [ids copy];
            self.sumbitParam.payAmount = [NSString stringWithFormat:@"%.2f", price];
        }
        
        if (self.locations.count >0) {
            [self.locations removeAllObjects];
        }
        
        [self.addressModel.list enumerateObjectsUsingBlock:^(Address * _Nonnull obj, NSUInteger addressIndex, BOOL * _Nonnull stop) {
            
            Address *defaultAddress = self.addressModel.list[addressIndex];
            [model.list enumerateObjectsUsingBlock:^(MeatPayOrderItem * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
                [item.ranges enumerateObjectsUsingBlock:^(Ranges * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    if (([defaultAddress.lon floatValue] <= [obj.longitude floatValue])
                        &&([defaultAddress.lat floatValue] <= [obj.latitude floatValue])) {
                        
                        [self.locations addObject:defaultAddress];
                    }
                }];
            }];
        }];
        
        if (self.isRefresh) {
            [self endRefresh];
        }
        
        if (model.list.count >0) {
            self.tableView.hidden = NO;
            self.footer.price = [NSString stringWithFormat:@"%.2f", price];
            [self.tableView reloadData];
            
        }else{
            [self loadNoData];
        }
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self loadErrorData];
    }];
}

//校验下单
- (void)checkOrders{
    
    @weakify(self);
    MeatOrderCheckParam *param = [[MeatOrderCheckParam alloc] init];
    param.memberId = kMemberId;
    param.data = @[self.listParam];
    [[self.meatApi getMeatPayOrderCheckByParams:param] subscribeNext:^(MeatPayModel * _Nullable model) {
        @strongify(self);
        
        if (model.list.count >0) {
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"当前有失效商品" message:@"手慢了，您的部分商品已被抢，是否要继续支付剩余商品？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }];
            [cancelAction setValue:UIColorFromRGB(0x363636) forKey:@"titleTextColor"];
            
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                
                MeatPayViewController *vc = [[MeatPayViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }];
            [okAction setValue:mMainColor forKey:@"titleTextColor"];
            
            
            [alert addAction:cancelAction];
            [alert addAction:okAction];
            [self presentViewController:alert animated:YES completion:nil];

        }else{
            MeatPayViewController *vc = [[MeatPayViewController alloc] init];
            vc.parma = self.sumbitParam;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } error:^(NSError * _Nullable error) {
    
        [self showHudWithMsg:@"222222"];
    }];
}

//下拉刷新
- (void)refresh
{
    [super refresh];
    [self initData];
}

#pragma mark - address.delegate
- (void)chooseLocation:(Address *)address index:(NSInteger)index{
    
    __block BOOL isNeedRefresh = NO;
    
    @weakify(self);
    [self.model.list enumerateObjectsUsingBlock:^(MeatPayOrderItem * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
        [item.ranges enumerateObjectsUsingBlock:^(Ranges * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            @strongify(self);
            
            if (([address.lon floatValue] <= [obj.longitude floatValue])
                &&([address.lat floatValue] <= [obj.latitude floatValue])) {
                
                if (self.locations.count >0) {
                    [self.locations removeAllObjects];
                }
                [self.locations addObject:address];
                isNeedRefresh = YES;
                [self localReloadTableViewBySection:0];
                return ;
            }
        }];
    }];
    
    if (!isNeedRefresh) {
        [self hanglingError1:@"您选择的地址不在配送范围，请重新选择"];
    }
}


#pragma mark - tableview delegate/dataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0) return 90;
    if(indexPath.section == 1) return 183;
    return 76;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section == 2 ?15 :10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *sectionView = [[UIView alloc] init];
    sectionView.backgroundColor = KClearColor;
    return sectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {
        case 0:
            {
                MeatOrderLocationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatOrderLocationCell"];
                cell.locations = [self.locations copy];
                
                @weakify(self);
                cell.addressBlock = ^(Address * _Nonnull address) {
                    @strongify(self);
                    self.sumbitParam.receiveAddressId = address.receiveAddressId;
                    self.sumbitParam.receiveAddress = [NSString stringWithFormat:@"%@%@", address.localName, address.details];
                    self.sumbitParam.addressDefaultIf = address.isDefault;
                };
                return cell;

            }
            break;
        case 1:
            {
                MeatOrderListCell *newsCell = [tableView dequeueReusableCellWithIdentifier:@"MeatOrderListCell"];
                newsCell.item = self.model.list[0];
                
                kWeakSelf(self);
                newsCell.editBlock = ^(NSInteger params) {
                    weakself.currentIndex = indexPath.section;
                    
                    [weakself showHudWithMsg:@"xxxxxx"];
                };
                return newsCell;

            }
            break;
            
        default:
            {
                MeatOrderPriceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MeatOrderPriceCell"];
                cell.item = self.model.list[0];
                return cell;

            }
            break;
    }
    
    return [UITableViewCell new];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.section) {
        case 0:
            {
                AddressViewController *vc = [[AddressViewController alloc] init];
                vc.delegate = self;
                vc.isOrderJump = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        case 1:
            {
                if (self.model.list.count >0) {
                    
                    MeatOrderBox *box = [[MeatOrderBox alloc] init];
                    box.item = self.model.list[0];
                    [box showView];
                }
            }
            break;
            
        default:
            {
            
            }
            break;
    }
    
}

#pragma mark - setter and getter

- (void)setSaleType:(NSNumber *)saleType{
    
    self.sumbitParam.orderClass = saleType;
}

- (MeatTipLabel *)tipLabel{
    if (!_tipLabel) {
        _tipLabel = [[MeatTipLabel alloc] init];
        _tipLabel.height = 34;
        
        NSString *contentStr = @"为保障您的财产安全，等小猪主人付清饲养费，预定单再付不迟哦！";
        _tipLabel.text = contentStr;
        [_tipLabel sizeToFit];
    }
    return _tipLabel;
}


- (MeatPayView *)footer{
    if (!_footer) {
        _footer = [[MeatPayView alloc] init];
        _footer.type = MeatPayType_Submit;
        
        //全选Block
        @weakify(self);
        //支付Block
        _footer.payCartBlock = ^{
            @strongify(self);
            [self checkOrders];
        };
        
    }
    return _footer;
}

- (UIButton *)anonymousBtn{
    
    if (!_anonymousBtn) {
        _anonymousBtn = [UIButton makeButtonWithText:@"  匿名购买" textColor:UIColorFromRGB(0x999999) font:mFont(13) textAliment:0 cornerRadius:0];
        [_anonymousBtn setImage:[UIImage imageNamed:@"meat_cart_unchecked"] forState:UIControlStateNormal];
        [_anonymousBtn setImage:[UIImage imageNamed:@"meat_pay_choosed"] forState:UIControlStateSelected];
        [_anonymousBtn addTarget:self action:@selector(chooseAnonymous:) forControlEvents:UIControlEventTouchUpInside];
        _anonymousBtn.backgroundColor = KClearColor;
        
    }
    return _anonymousBtn;
}


- (void)chooseAnonymous:(UIButton *)sender{
    
    sender.selected = !sender.selected;
    self.sumbitParam.memberStatus = sender.selected ?@2 :@1;
}

- (MeatMarketApi *)meatApi{
    
    if(!_meatApi){
        _meatApi = [[MeatMarketApi alloc]init];
    }
    return _meatApi;
}

- (MeatPayOrderModel *)model{
    
    if (!_model) {
        _model = [[MeatPayOrderModel alloc] init];
    }
    return _model;
}


- (AddressList *)addressModel{
    
    if (!_addressModel) {
        _addressModel = [[AddressList alloc] init];
    }
    return _addressModel;
}


- (NSMutableArray *)locations{
    
    if (!_locations) {
        _locations = [NSMutableArray array];
    }
    return _locations;
}


- (ListParam *)listParam{
    
    if (!_listParam) {
        _listParam = [[ListParam alloc] init];
        _listParam.shopId = [NSString stringWithFormat:@"%@", self.shopId];
    }
    return _listParam;
}

- (MeatOrderSumbitParam *)sumbitParam{
    
    if (!_sumbitParam) {
        _sumbitParam = [[MeatOrderSumbitParam alloc] init];
        _sumbitParam.memberId = kMemberId;
        _sumbitParam.shopId = self.shopId;
        _sumbitParam.remark = @"";
        _sumbitParam.goType = @"4";
        _sumbitParam.memberStatus = @1;
    }
    return _sumbitParam;
}


#pragma mark - override methods

- (void)registerTableViewCell{
    
    [self.tableView registerClass:[MeatOrderListCell class] forCellReuseIdentifier:@"MeatOrderListCell"];
    [self.tableView registerClass:[MeatOrderLocationCell class] forCellReuseIdentifier:@"MeatOrderLocationCell"]; //MeatOrderPriceCell
    [self.tableView registerClass:[MeatOrderPriceCell class] forCellReuseIdentifier:@"MeatOrderPriceCell"]; //MeatOrderPriceCell
    self.tableView.mj_footer.hidden = YES;
    self.tableView.height = KScreenHeight - (TJ_NavBarHeight);

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 10)];
    view.backgroundColor = mBackgroudColor;
    self.tableView.tableFooterView = view;
}

- (void)loadErrorData
{
    [super loadErrorData];
    self.footer.hidden = YES;
}

- (void)loadNoData
{
    [super loadNoData];
    self.footer.hidden = YES;
}


- (void)endLoadMore{
    [super endLoadMore];
    self.footer.hidden = NO;
}

- (void)endRefresh{
    [super endRefresh];
    self.footer.hidden = NO;
    
}

- (void)endLoadMoreMoData
{
    [super endLoadMoreMoData];
    self.footer.hidden = NO;
}

#pragma mark - other methods

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    [self.view endEditing:YES];
//    CGFloat sectionHeaderHeight = 10;
//    if(scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
//        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
//        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
//    }
//}


#pragma mark - notification methods

- (void)textFieldTextChanged:(NSNotification *)notification
{
    UITextField *textField = notification.object;
    self.sumbitParam.remark = textField.text;
}

- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];

    kWeakSelf(self);
    [UIView animateWithDuration:duration animations:^{
        weakself.tableView.mj_y = 0;
    }];

    //当键盘升起的时候添加点击降落操作
    if (!self.tap) {
        self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    }
    [self.view addGestureRecognizer:self.tap];
}

//取消键盘响应
- (void)hideKeyboard{
    
    [self.view endEditing:YES];
}


- (void)keyboardWillHide:(NSNotification *)notification{
    
    if (self.tap) {
        [self.view removeGestureRecognizer:self.tap];
    }
    self.tableView.mj_y = TJ_NavBarHeight;

}


//添加键盘通知
- (void)addkeyBoardNotification{
    
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter addObserver:self selector:@selector(textFieldTextChanged:) name:UITextFieldTextDidChangeNotification object:nil];
}

//移除键盘通知
- (void)removeKeyboardNotification{
    
    [kNotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [kNotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [kNotificationCenter removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)dealloc{
    
    [self removeKeyboardNotification];
}


@end
